﻿Imports System.ComponentModel
Imports System.IO
Imports System.Data.SQLite

Namespace OfflineLibrary_WPF
	Public Enum BrowseModes
		<Description("Offline")> Offline
		<Description("Offline - Get Missing Page")> OfflineGetMissingPage
		<Description("Offline - Get Linked Pages")> OfflineGetLinkedPages
		<Description("Online")> Online
		<Description("Online - Get Linked Pages")> OnlineGetLinkedPages
	End Enum

	Module Settings

		Public Property BrowseMode As BrowseModes
			Get
				Dim myBrowseMode As BrowseModes
				Try
					If My.Settings.BrowseMode = "" Then
						myBrowseMode = BrowseModes.Offline
					Else
						myBrowseMode = CType(My.Settings.BrowseMode, BrowseModes)
					End If
				Catch ex As InvalidCastException
					myBrowseMode = BrowseModes.Offline
				Catch ex As OverflowException
					myBrowseMode = BrowseModes.Offline
				End Try

				Return myBrowseMode
			End Get
			Set(value As BrowseModes)
				My.Settings.BrowseMode = value
			End Set
		End Property

		'Public ReadOnly Property EnumBrowseModes() As IEnumerable(Of Object)
		'	Get
		'		Return GetEnum(Of BrowseModes)()
		'	End Get
		'End Property

		Private _SavedProductName As String = My.Application.Info.ProductName
		Public Property LocalFileLocation As IO.DirectoryInfo
			Get
				Dim _LocalFileLocation As IO.DirectoryInfo
				If My.Settings.StorageLocation = "" Then
					_LocalFileLocation = New IO.DirectoryInfo(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location) & IO.Path.DirectorySeparatorChar & "data")
					'If _LocalFileLocation.FullName.Contains(" ") Then
					'	_LocalFileLocation = New IO.DirectoryInfo(System.IO.Path.GetPathRoot(System.Reflection.Assembly.GetExecutingAssembly.Location) & IO.Path.DirectorySeparatorChar & "OfflineBrowserData")
					'End If
					'If _LocalFileLocation.FullName.Contains(" ") Then
					'	_LocalFileLocation = New IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\" & _SavedProductName)
					'End If
				Else
					_LocalFileLocation = New IO.DirectoryInfo(My.Settings.StorageLocation)
				End If
				If Not _LocalFileLocation.Exists Then
					Try
						_LocalFileLocation.Create()
					Catch ex As IOException
						'if we couldn't write to that folder, create a new folder off the root of the disk to write data to
						_LocalFileLocation = New IO.DirectoryInfo(System.IO.Path.GetPathRoot(System.Reflection.Assembly.GetExecutingAssembly.Location) & IO.Path.DirectorySeparatorChar & "OfflineBrowserData")
						If Not _LocalFileLocation.Exists Then
							_LocalFileLocation.Create()
						End If
					End Try
				End If

				Return _LocalFileLocation
			End Get
			Set(value As IO.DirectoryInfo)
				My.Settings.StorageLocation = value.FullName
			End Set
		End Property

		Public ReadOnly Property OfflineDatabaseFileInfo As IO.FileInfo
			Get
				Return New IO.FileInfo(IO.Path.Combine(LocalFileLocation.FullName, "OfflineData.sqlite"))
			End Get
		End Property

		Public ReadOnly Property OfflineDataConnectionString As String
			Get
				Return String.Format("data source={0}", OfflineDatabaseFileInfo.FullName)
			End Get
		End Property

		Public Sub SetOfflineDataDatabase()
			Dim copyComplete As Boolean = False
			Dim database As IO.FileInfo = OfflineDatabaseFileInfo

			'If Not database.Exists Then
			'	IO.File.Copy(database.Name, database.FullName)
			'End If

			'Dim watcher As New FileSystemWatcher(database.DirectoryName, database.Name)
			'AddHandler watcher.Changed, Sub(sender, e)
			'								Dim file__1 As FileStream = Nothing
			'								Try
			'									System.Threading.Thread.Sleep(100)
			'									' hack for timing issues
			'									file__1 = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read)
			'								Catch generatedExceptionName As IOException
			'									' we couldn't open the file
			'									' this is probably because the copy operation is not done
			'									' just swallow the exception

			'									' now we have a handle to the file
			'									copyComplete = True
			'								End Try

			'							End Sub


			If Not database.Exists Then

				Using conn As New SQLiteConnection(OfflineDataConnectionString)
					conn.Open()
					Dim sql As String

					sql = "INSERT OR REPLACE INTO PageData (URL, HTML, LastUpdated) VALUES (@URL, @HTML, @LastUpdated)"
					Using cmd As New SQLiteCommand(conn)
						cmd.CommandText = "CREATE TABLE ""Languages"" (""LanguageCode"" TEXT PRIMARY KEY  NOT NULL  UNIQUE , ""Language"" TEXT NOT NULL  UNIQUE )"
						cmd.ExecuteNonQuery()

						cmd.CommandText = "CREATE TABLE ""PageData"" (""URL"" TEXT PRIMARY KEY  NOT NULL  UNIQUE , ""HTML"" BLOB, ""LastUpdated"" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)"
						cmd.ExecuteNonQuery()

						cmd.CommandText = "CREATE VIRTUAL TABLE ""PageSearchData"" USING FTS4(""URL"" TEXT PRIMARY KEY  NOT NULL  UNIQUE, ""PageTitle"" TEXT, , ""PageText"" TEXT, ""LastUpdated"" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)"
						cmd.ExecuteNonQuery()

					End Using
				End Using
			End If

		End Sub

	End Module
End Namespace